package com.ls.lserp.modules.inventoryControl.web;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import freemarker.template.Configuration;
import groovy.util.ResourceException;

import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.support.RequestContext;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.inventoryControl.entity.InventoryEntity;
import com.ls.lserp.modules.inventoryControl.entity.OginzationEntity;
import com.ls.lserp.modules.inventoryControl.service.InventoryService;
import com.ls.lserp.modules.order.entity.OrderMateriel;
import com.ls.lserp.modules.sys.entity.Dict;
import com.ls.lserp.modules.sys.utils.DictUtils;

@Controller
@RequestMapping(value = "${adminPath}/stock/warning")
public class InventoryController extends BaseController {

	// 保存 编辑 删除 方法
	@Autowired
	private InventoryService inventoryService;
	@Autowired
	Configuration freemarkerConfiguration;

	@ModelAttribute
	public InventoryEntity get(@RequestParam(required = false) String id) {

		// 判断id是否为空
		if (StringUtils.isNotBlank(id)) {

			// 执行查询语句 查询基本信息
			return inventoryService.get(Long.parseLong(id));
		} else {

			// 若为空，实例化
			return new InventoryEntity();
		}
	}

	/**
	 * @Title: 画面跳转用
	 * @return url
	 */
	@RequiresPermissions("stock:warning:view")
	@RequestMapping(value = { "" })
	public String list(Model model) {
		//客户供货商
		List<OrderMateriel> venderList = inventoryService.findVenderList(new OrderMateriel());
		model.addAttribute("venderList", venderList);
		// 物料类别
		List<Dict> categoryList = DictUtils.getDictList(ResourcesUtil.getConfig("categoryCD"));
		model.addAttribute("categoryList", categoryList);
		// 业务类别
		List<Dict> businessTypeList = DictUtils.getDictList(ResourcesUtil.getConfig("business_Type"));
		model.addAttribute("businessType", businessTypeList);
		// 画面跳转
		return "modules/inventoryControl/inventoryWarning";
	}

	/**
	 * @Title: 画面跳转用
	 * @return url
	 */
	@RequiresPermissions("stock:warning:view")
	@RequestMapping(value = { "toShowMessage" })
	public String toShowMessage(InventoryEntity inventoryEntity, Model model) {
		OrderMateriel orderMateriel = new  OrderMateriel();
		orderMateriel.setMaterialId((long)inventoryEntity.getMaterialId());
		inventoryEntity.setMaterialReserverKbn(ResourcesUtil.getConfig("reserverAlert_10"));
		BigDecimal unusableMQuantity = inventoryService.sumMaterialQuantity(orderMateriel);
		//客户供货商
		List<OrderMateriel> venderList = inventoryService.findVenderList(new OrderMateriel());
		//获取明细数据
		List<InventoryEntity> inventoryList = inventoryService.findReservserAlertDetail(inventoryEntity);
		model.addAttribute("unusableMQuantity", unusableMQuantity);
		model.addAttribute("venderList", venderList);
		model.addAttribute("inventoryList", inventoryList);
		model.addAttribute("item", inventoryEntity);
		// 画面跳转
		return "modules/inventoryControl/inventoryWarningShow";
	}

	/**
	 * @Title: 新建编辑保存
	 * @Description: 检索
	 * @param inventoryEntity
	 * @param response
	 * @return url
	 */
	@RequiresPermissions("stock:warning:edit")
	@RequestMapping(value = "saveData")
	@ResponseBody
	public String saveData(InventoryEntity inventoryEntity,HttpServletResponse response) throws ResourceException {
		try {
			// 更新预警面辅料表
			inventoryService.insertInventory(inventoryEntity);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			// 返回提示信息
			return renderString(response, AjaxDone.error(getText("warehouse_edit_save_msg_fail")));
		}

		// ajax返回结果
		// 保存成功返回提示信息
		return renderString(response, AjaxDone.ok(
				SystemMessageUtils.getMessageName( "warehouse_edit_save_msg_success")));

	}

	/**
	 * @Title: 画面检索
	 * @Description: 查询页面
	 * @param inventoryEntity
	 * @param request
	 * @param response
	 * @param model
	 * @return searchList
	 * @throws Exception
	 */
	@RequiresPermissions("stock:warning:view")
	@RequestMapping(value = { "searchList" })
	@ResponseBody
	public String searchList(InventoryEntity inventoryEntity, HttpServletRequest request, HttpServletResponse response,
			Model model) throws Exception {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		// ajax回调时使用的一览list名
		request.setAttribute(Global.LIST_NAME, "inventory");
		// 画面取得的检索项目
		// 原辅料中文名称
		String materialNameCn = inventoryEntity.getMaterialNameCn();
		// 物料类别
		String materialTypeCd = inventoryEntity.getMaterialTypeCd();
		// 业务类别
		String businessType = inventoryEntity.getBusinessType();
		// 日期
		Date dateFrom = inventoryEntity.getDateFrom();
		// 日期
		Date dateTo = inventoryEntity.getDateTo();
		// 状态区分(0-预订 1-预订完成 9-采购完成 默认0)
		String materialStatus = inventoryEntity.getMaterialStatus();
		// 拼接字符串供分页使用
		StringBuilder searchParam = new StringBuilder();
		searchParam.append("&materialNameCn=");
		searchParam.append(materialNameCn);
		searchParam.append("&materialTypeCd=");
		searchParam.append(materialTypeCd);
		searchParam.append("&businessType=");
		searchParam.append(businessType);
		searchParam.append("&dateFrom=");
		searchParam.append(dateFrom);
		searchParam.append("&dateTo=");
		searchParam.append(dateTo);
		searchParam.append("&materialStatus=");
		searchParam.append(materialStatus);
		// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam.toString());
		// 查询一览页面数据
		Page<InventoryEntity> page = inventoryService.findList(new Page<InventoryEntity>(request, response),
				inventoryEntity);
		// 读取系统路径
		// 读取文件生成字符串
		String strUri = request.getContextPath() + Global.getAdminPath();
		String strHtml = "";
		Map<String, Object> map = new HashedMap();
		map.put("adminUri", strUri);
		map.put("users", page.getList());
		map.put("pageNo", page.getPageNo());
		map.put("pageSize", page.getPageSize());
		map.put("springMacroRequestContext", new RequestContext (request));
		strHtml = createHtml(map, "inventoryControllFtl.ftl");
		listMap.put("inventory", strHtml);
		listMap.put("page", page.getHtml());
		// ajax返回结果
		return renderString(response, listMap);
	}

	/**
	 * @Title: 生成HTML
	 * @return HTML
	 */
	public String createHtml(Map<String, Object> map, String fileName) {
		String tempHtml = "";
		try {
			tempHtml = FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfiguration.getTemplate(fileName),
					map);
		} catch (Exception e) {
			return tempHtml;
		}
		return tempHtml;
	}
	
	/**
	 * @Title: 新建编辑保存
	 * @Description: 检索
	 * @param inventoryEntity
	 * @param response
	 * @return url
	 */
	@RequiresPermissions("stock:warning:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(String alertId,HttpServletResponse response) throws ResourceException {
		try {
			// 更新预警面辅料表
			inventoryService.deleteAlertReserve(alertId);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			// 返回提示信息
			return renderString(response, AjaxDone.error(getText("warehouse_edit_save_msg_fail")));
		}

		// ajax返回结果
		// 保存成功返回提示信息
		return renderString(response, AjaxDone.ok(
				SystemMessageUtils.getMessageName( "warehouse_edit_save_msg_success")));

	}
}
